package com.example.demo.service.impl;

import com.example.demo.bean.Department;
import com.example.demo.common.ServerResponse;
import com.example.demo.dao.DepartmentRepository;
import com.example.demo.service.DepartmentService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * Created by IntelliJ IDEA.
 *
 * @author ouyangzhixiang
 * @date 2018/6/22
 */
@Service
@AllArgsConstructor
public class DepartmentServiceImpl implements DepartmentService {

    private final DepartmentRepository departmentRepository;

    @Override
    public ServerResponse getFindOne(Integer id) {
        Optional<Department> departmentCount = departmentRepository.findById(id);
        if (departmentCount.isPresent()) {
            return ServerResponse.createBySuccess(departmentCount);

        }
        return ServerResponse.createByErrorMessage("没有找到相关部门");
    }

    /**
     * 查找部门信息列表
     *
     * @param parentId 父节点Id
     * @return
     */
    @Override
    public ServerResponse<List<Department>> selectId(Integer parentId) {
        List<Department> listServerResponse = departmentRepository.findByParentIdOrderByIdDesc(parentId);
        if (listServerResponse.isEmpty()) {
            return ServerResponse.createByErrorMessage("没有找到Id");
        }
        return ServerResponse.createBySuccess(listServerResponse);
    }

    /**
     * 添加部门数据
     *
     * @param department
     * @return
     */
    @Override
    public ServerResponse<Department> addDepartment(Department department) {
        Department departments = departmentRepository.save(department);
        return ServerResponse.createBySuccessMessage("添加成功", departments);
    }

    /**
     * 删除部门
     *
     * @param id
     */
    @Override
    public void deleteDepartment(Integer id) {
        departmentRepository.deleteById(id);
    }

    /**
     * 更新部门数据
     *
     * @param department
     * @return
     */
    @Override
    public ServerResponse<Department> departmentUpdate(Department department) {
        Department departmentUpdate = new Department();
        departmentUpdate.setId(department.getId());
        departmentUpdate.setName(department.getName());
        departmentUpdate.setParentId(department.getParentId());
        department = departmentRepository.save(departmentUpdate);
        return ServerResponse.createBySuccessMessage("更新成功", department);
    }
}
